package Controller;

import Model.Team;
import View.Window;
import java.io.*;
import java.net.*;
import javax.swing.JOptionPane;

public class Client implements Runnable {

    private ObjectOutputStream output;
    private ObjectInputStream input;
    private String server;
    private Socket client;
    private Window g;

    public Client(Window a, String server) {
	this.server = server;
	this.g = a;
    }

    public void runClient() {
	try {

	    connectToServer();

	    getStreams();

	    processConnection();

	    closeConnection();
	} catch (EOFException eof) {
	    JOptionPane.showMessageDialog(null, "Connection closed by server!");
	} catch (IOException io) {
	    System.out.println("I/O Error!");
	}
    }

    private void getStreams() throws IOException {
	output = new ObjectOutputStream(client.getOutputStream());
	output.flush();
	input = new ObjectInputStream(client.getInputStream());
    }

    private void connectToServer() throws IOException {

	client = new Socket(server, 15000);
	JOptionPane.showMessageDialog(null, "Connected to: " + client.getInetAddress().getHostName());
    }

    private void processConnection() throws IOException {
	boolean flag = true;
	Object obj;

	do {

	    try {
		obj = input.readObject();
		if (obj.getClass().equals(Team.class)) {
		    Team team = (Team) obj;
		    g.Match.setHomeTeam(team);
		    g.AfterSimulation();
		} else if (obj.getClass().equals(String.class)) {
		    System.out.println("Server> " + (String) obj);
		} else {
		    int i = 0;
		    while (((boolean[]) obj).length > i && 10>i) {
			if (g.Match.getHomeTeam().isStarting(i) != ((boolean[]) obj)[i]) {
			    g.Match.getHomeTeam().ChangeStatus(i);
			}
			i++;
		    }
		    g.AfterSimulation();
		}
	    } catch (ClassNotFoundException classNotFound) {
		System.out.println("Wrong object recivied!");
	    }

	} while (flag);
    }

    private void closeConnection() throws IOException {
	JOptionPane.showMessageDialog(null, "You are disconnecting from the server.");
	output.close();
	input.close();
	client.close();
    }

    public void sendData(Object data) {
	try {

	    output.writeObject(data);
	    output.flush();
	} catch (IOException io) {
	    JOptionPane.showMessageDialog(null, "Can't send your team data!");
	    io.printStackTrace();
	}
    }

    @Override
    public void run() {
	System.out.println("cliente");
	runClient();
    }
}